<template>
  <div class="return">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>还车处理</span>
          <div class="header-operations">
            <el-input
              v-model="searchQuery"
              placeholder="搜索车辆品牌"
              style="width: 200px; margin-right: 10px"
            />
          </div>
        </div>
      </template>

      <el-table :data="filteredReturnList" style="width: 100%">
        <el-table-column prop="id" label="车辆ID" width="100" />
        <el-table-column prop="carInfo" label="车辆信息" width="180" />
        <el-table-column prop="mileage" label="当前里程" width="120" />
        <el-table-column prop="lastMaintenance" label="上次保养" width="180" />
        <el-table-column prop="nextMaintenance" label="下次保养" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              v-if="scope.row.status === '待还车'"
              @click="handleReturn(scope.row)"
            >
              处理还车
            </el-button>
            <el-button 
              size="small" 
              type="info" 
              @click="handleViewDetails(scope.row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 还车处理对话框 -->
    <el-dialog
      v-model="returnDialogVisible"
      title="处理还车"
      width="500px"
      class="return-dialog"
    >
      <el-form 
        :model="returnForm" 
        label-width="120px" 
        :rules="returnRules" 
        ref="returnFormRef"
        class="return-form"
      >
        <el-form-item label="实际归还日期" prop="actualReturnDate">
          <el-date-picker
            v-model="returnForm.actualReturnDate"
            type="date"
            placeholder="选择实际归还日期"
            style="width: 100%"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="增加的里程数" prop="mileage">
          <el-input-number 
            v-model="returnForm.mileage" 
            :min="0" 
            style="width: 100%"
            placeholder="请输入增加的里程数"
          />
        </el-form-item>
        <el-form-item label="车辆状况" prop="condition">
          <el-select 
            v-model="returnForm.condition" 
            placeholder="请选择车辆状况" 
            style="width: 100%"
          >
            <el-option label="良好" value="良好" />
            <el-option label="需要维修" value="需要维修" />
          </el-select>
        </el-form-item>
        <el-form-item 
          label="损坏原因" 
          prop="damageDescription" 
          v-if="returnForm.condition === '需要维修'"
        >
          <el-input
            v-model="returnForm.damageDescription"
            type="textarea"
            :rows="3"
            placeholder="请描述车辆损坏原因"
          />
        </el-form-item>
        <el-form-item 
          label="维修金额" 
          prop="repairCost" 
          v-if="returnForm.condition === '需要维修'"
        >
          <el-input-number 
            v-model="returnForm.repairCost" 
            :min="0" 
            :precision="2"
            style="width: 100%"
            placeholder="请输入维修金额"
          />
        </el-form-item>
        <el-form-item 
          label="维修人员" 
          prop="technicianId" 
          v-if="returnForm.condition === '需要维修'"
        >
          <el-select 
            v-model="returnForm.technicianId" 
            placeholder="请选择维修人员"
            style="width: 100%"
          >
            <el-option
              v-for="tech in technicianOptions"
              :key="tech.id"
              :label="tech.name"
              :value="tech.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="returnDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleReturnSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 还车详情对话框 -->
    <el-dialog
      v-model="detailsDialogVisible"
      title="还车详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="租赁ID">{{ currentReturn.id }}</el-descriptions-item>
        <el-descriptions-item label="客户姓名">{{ currentReturn.customerName }}</el-descriptions-item>
        <el-descriptions-item label="车辆信息">{{ currentReturn.carInfo }}</el-descriptions-item>
        <el-descriptions-item label="开始日期">{{ currentReturn.startDate }}</el-descriptions-item>
        <el-descriptions-item label="结束日期">{{ currentReturn.endDate }}</el-descriptions-item>
        <el-descriptions-item label="实际归还日期">{{ currentReturn.actualReturnDate }}</el-descriptions-item>
        <el-descriptions-item label="里程数">{{ currentReturn.mileage }}</el-descriptions-item>
        <el-descriptions-item label="车辆状况">{{ currentReturn.condition }}</el-descriptions-item>
        <el-descriptions-item label="损坏描述" :span="2">{{ currentReturn.damageDescription }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const returnList = ref([])
const searchQuery = ref('')

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取还车处理列表
const fetchReturnList = async () => {
  console.log('开始获取还车处理列表...')
  try {
    const token = localStorage.getItem('Token')
    const url = new URL('http://localhost:8080/car/list')
    
    // 添加分页参数
    url.searchParams.append('page', currentPage.value)
    url.searchParams.append('size', pageSize.value)
    url.searchParams.append('status', '2')  // 状态为2表示已租出
    
    // 添加搜索参数
    if (searchQuery.value) {
      url.searchParams.append('brand', searchQuery.value)  // 修改为brand参数
    }

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })
    
    if (response.status === 401) {
      // token 过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    console.log('获取还车处理列表成功，原始数据：', result)
    
    if (result.code === 200) {
      // 转换数据结构
      returnList.value = (result.data.records || []).map(car => ({
        id: car.id,
        customerName: '待获取', // 需要从租赁记录中获取
        carInfo: `${car.brand} ${car.model} ${car.plateNumber}`,
        startDate: '待获取', // 需要从租赁记录中获取
        endDate: '待获取', // 需要从租赁记录中获取
        actualReturnDate: '',
        status: '待还车',
        mileage: car.mileage,
        lastMaintenance: car.lastMaintenance || '暂无记录',
        nextMaintenance: car.nextMaintenance || '暂无记录',
        condition: '',
        damageDescription: '',
        remark: ''
      }))
      total.value = result.data.total || 0
      currentPage.value = result.data.current || 1
      pageSize.value = result.data.size || 10
      console.log('处理后的还车处理列表数据：', returnList.value)
    } else {
      throw new Error(result.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取还车处理列表失败：', error)
    ElMessage.error('获取还车处理列表失败：' + error.message)
  }
}

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchReturnList()
}

// 处理每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchReturnList()
}

// 监听搜索条件变化
watch([searchQuery], () => {
  currentPage.value = 1 // 重置页码
  fetchReturnList()
})

// 在组件挂载时获取还车处理列表
onMounted(() => {
  console.log('组件已挂载，准备获取还车处理列表')
  fetchReturnList()
  fetchTechnicianList()
})

const filteredReturnList = computed(() => {
  return returnList.value.filter(item => {
    if (!item) return false
    const matchSearch = (item.carInfo || '').includes(searchQuery.value)
    return matchSearch
  })
})

// 还车处理相关
const returnDialogVisible = ref(false)
const returnFormRef = ref(null)
const returnForm = reactive({
  actualReturnDate: new Date().toISOString().split('T')[0],
  mileage: 0,
  condition: '良好',
  damageDescription: '',
  repairCost: 0,
  technicianId: ''
})

const returnRules = {
  actualReturnDate: [{ required: true, message: '请选择实际归还日期', trigger: 'change' }],
  mileage: [{ required: true, message: '请输入增加的里程数', trigger: 'change' }],
  condition: [{ required: true, message: '请选择车辆状况', trigger: 'change' }],
  damageDescription: [{ required: true, message: '请描述车辆损坏原因', trigger: 'blur' }],
  repairCost: [{ required: true, message: '请输入维修金额', trigger: 'change' }],
  technicianId: [{ required: true, message: '请选择维修人员', trigger: 'change' }]
}

// 维修人员选项
const technicianOptions = ref([])

// 获取维修人员列表
const fetchTechnicianList = async () => {
  try {
    const token = localStorage.getItem('Token')
    const response = await fetch('http://localhost:8080/employee/names', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })
    
    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    if (result.code === 200) {
      // 将字符串数组转换为对象数组，使用索引作为id
      technicianOptions.value = (result.data || []).map((name, index) => ({
        id: index + 1,
        name: name
      }))
    } else {
      throw new Error(result.message || '获取维修人员列表失败')
    }
  } catch (error) {
    console.error('获取维修人员列表失败：', error)
    ElMessage.error('获取维修人员列表失败：' + error.message)
  }
}

// 还车详情相关
const detailsDialogVisible = ref(false)
const currentReturn = ref({})

// 获取租赁信息
const fetchRentalInfo = async (carId) => {
  try {
    const token = localStorage.getItem('Token')
    const url = new URL('http://localhost:8080/rental/list')
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Token': token
      }
    })
    
    if (response.status === 401) {
      localStorage.removeItem('Token')
      localStorage.removeItem('user')
      window.location.href = '/login'
      return
    }
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    if (result.code === 200) {
      // 查找对应车辆的租赁记录
      const rental = result.data.records.find(r => r.carId === carId)
      if (rental) {
        // 更新租赁相关信息，但保留里程数
        const mileage = currentReturn.value.mileage
        currentReturn.value = {
          id: rental.id,
          customerName: rental.customerName,
          carInfo: rental.carInfo,
          startDate: rental.startRentalTime,
          endDate: rental.endRentalTime,
          actualReturnDate: rental.actualReturnTime || '未归还',
          mileage: mileage, // 保持使用还车列表中的里程数
          condition: rental.condition || '暂无记录',
          damageDescription: rental.damageDescription || '暂无记录'
        }
      } else {
        ElMessage.warning('未找到相关租赁记录')
      }
    } else {
      throw new Error(result.message || '获取租赁信息失败')
    }
  } catch (error) {
    console.error('获取租赁信息失败：', error)
    ElMessage.error('获取租赁信息失败：' + error.message)
  }
}

const handleViewDetails = async (row) => {
  // 先设置基本信息
  currentReturn.value = {
    id: '待获取',
    customerName: '待获取',
    carInfo: row.carInfo,
    startDate: '待获取',
    endDate: '待获取',
    actualReturnDate: '未归还',
    mileage: row.mileage, // 使用还车列表中的当前里程
    condition: '暂无记录',
    damageDescription: '暂无记录'
  }
  
  // 获取租赁信息
  await fetchRentalInfo(row.id)
  detailsDialogVisible.value = true
}

// 添加当前处理的车辆ID
const currentCarId = ref(null)

const handleReturn = (row) => {
  currentCarId.value = row.id
  returnDialogVisible.value = true
}

const handleReturnSubmit = async () => {
  if (!returnFormRef.value) return
  
  await returnFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const token = localStorage.getItem('Token')
        
        // 构建请求URL
        const updateStatusUrl = new URL(`http://localhost:8080/car/updateStatus/${currentCarId.value}`)
        // 根据车辆状况设置不同的状态值
        updateStatusUrl.searchParams.append('status', returnForm.condition === '良好' ? '2' : '3')
        updateStatusUrl.searchParams.append('mileage', returnForm.mileage)
        updateStatusUrl.searchParams.append('returnTime', returnForm.actualReturnDate)
        
        // 如果车辆需要维修，添加维修相关信息
        if (returnForm.condition === '需要维修') {
          updateStatusUrl.searchParams.append('repairReason', returnForm.damageDescription)
          updateStatusUrl.searchParams.append('repairMoney', returnForm.repairCost)
          // 获取选中的维修人员姓名
          const selectedTech = technicianOptions.value.find(tech => tech.id === returnForm.technicianId)
          if (selectedTech) {
            updateStatusUrl.searchParams.append('employeeName', selectedTech.name)
          }
        }

        const response = await fetch(updateStatusUrl, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
            'Token': token
          }
        })

        if (response.status === 401) {
          localStorage.removeItem('Token')
          localStorage.removeItem('user')
          window.location.href = '/login'
          return
        }

        if (!response.ok) {
          throw new Error(`更新车辆状态失败: ${response.status}`)
        }

        const result = await response.json()
        if (result.code === 200) {
          ElMessage.success('还车处理成功')
          returnDialogVisible.value = false
          // 刷新列表
          fetchReturnList()
        } else {
          throw new Error(result.message || '更新车辆状态失败')
        }
      } catch (error) {
        console.error('还车处理失败：', error)
        ElMessage.error('还车处理失败：' + error.message)
      }
    }
  })
}

const getStatusType = (status) => {
  const statusMap = {
    '待还车': 'warning',
    '已还车': 'success'
  }
  return statusMap[status]
}
</script>

<style scoped>
.return {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 添加新的样式 */
.return-dialog :deep(.el-dialog__body) {
  padding: 20px 30px;
}

.return-form :deep(.el-form-item) {
  margin-bottom: 22px;
}

.return-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.return-form :deep(.el-input__wrapper),
.return-form :deep(.el-textarea__inner) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.return-form :deep(.el-input__wrapper:hover),
.return-form :deep(.el-textarea__inner:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.return-form :deep(.el-input__wrapper:focus-within),
.return-form :deep(.el-textarea__inner:focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

.return-form :deep(.el-select .el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.return-form :deep(.el-select .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.return-form :deep(.el-select .el-input__wrapper:focus-within) {
  box-shadow: 0 0 0 1px #409eff inset;
}
</style> 